package com.daniel.memo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.daniel.database.Database;


import android.R.integer;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TodoViewActivity extends ListActivity{
	
	private TaskAdapter taskAdapter;
	private List<Task> taskList;

	private Database db;
	private int todoRowId;

	private boolean isDeleteModeOn;

	private Button deleteTaskBtn;
	private Button cancelDeleteTaskBtn;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todo_list_view);

        db = new Database(this);
        isDeleteModeOn = false;

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
        	todoRowId = extras.getInt(Todo.TODO_ID);
        }
        
        registerForContextMenu(getListView());

        connectInput();
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	db.open();
    	updateList();
    }
 
    @Override
    public void onStop() {
    	super.onStop();
    	db.close();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	getMenuInflater().inflate(R.menu.todo_list_option_menu , menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.todo_add_task_id:
    			startAddTaskViewActivity();
    			return true;
    		default:
    			return super.onOptionsItemSelected(item);
    	}	
    }
    
    @Override 
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.todo_option_delete:
    			if (isDeleteModeOn == false) {
    				isDeleteModeOn = true;
    				switchToDeleteMode();
    				
    			} else {
    				isDeleteModeOn = false;
    				switchToNormalMode();
    				
    			}
    			updateList();
    			return true;
    			
    		case R.id.todo_option_delete_completed:
    			int totalDeletedTasks = deleteCompleted();
    			updateList();
    			Toast.makeText(getApplicationContext(), "Total " + totalDeletedTasks + " tasks are deleted.", Toast.LENGTH_SHORT).show();
    			return true;
    			
    		case R.id.todo_option_sort:	
    			return true;
    			
    	}
    	return super.onMenuItemSelected(featureId, item);
    }
    
    public int deleteCompleted() {
    	List<Task> tempTaskList = taskAdapter.getTaskList();
    	int deletedTaskCount = 0;
    	int taskId, memoId;
    	
    	for (int i = 0; i < tempTaskList.size(); i++) {
    		Task tempTask = tempTaskList.get(i);
    		if (tempTask.getIsCompleted() == true) {
    			taskId = tempTask.getTaskId();
    			memoId = tempTask.getMemoId();
    			
    			db.deleteTaskById(taskId, memoId);
    			deletedTaskCount++;    			
    		}
    	}
    	return deletedTaskCount;
    }
    
    
    //initialize item list
    public void updateList() {
    	taskList = new ArrayList<Task>();
    	Cursor tasksCursor = db.fetchTasksWithTodoId(todoRowId);
    	Cursor memoCursor;
    	Task tempTask;
    	
    	while (tasksCursor.moveToNext()) {
    		int memoId = tasksCursor.getInt(1);

    		memoCursor = db.fetchMemoById(memoId);
    		memoCursor.moveToFirst();

    		String taskTitle = memoCursor.getString(0);
    		String taskMemo = memoCursor.getString(2);
    		int taskId = tasksCursor.getInt(0);
    		String notiDate = tasksCursor.getString(3);
    		boolean intIsAramOn = tasksCursor.getInt(4) != 0;
    		int priority = tasksCursor.getInt(5);
    		boolean isCompleted = tasksCursor.getInt(6) != 0;

    		tempTask = new Task(taskTitle, taskMemo, taskId, memoId, priority, notiDate, intIsAramOn, isCompleted);

    		taskList.add(tempTask);
    	}

    	taskAdapter = new TaskAdapter(this, R.layout.task_row, taskList);
    	setListAdapter(taskAdapter);
    }

    public void connectInput() {
    	deleteTaskBtn = (Button) findViewById(R.id.delete_task_btn_id);
    	deleteTaskBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				int numOfDeleted = deleteSelectTask();
				isDeleteModeOn = false;
				switchToNormalMode();
				updateList();
				
				Toast.makeText(getApplicationContext(), "Total " + numOfDeleted + " tasks are deleted.", Toast.LENGTH_SHORT).show();
			}
		});
    	
    	cancelDeleteTaskBtn = (Button) findViewById(R.id.cancel_delete_task_btn_id);
    	cancelDeleteTaskBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				isDeleteModeOn = false;
				switchToNormalMode();
				updateList();
			}
		});
    }
    
    public void switchToDeleteMode() {
    	deleteTaskBtn.setVisibility(View.VISIBLE);
    	cancelDeleteTaskBtn.setVisibility(View.VISIBLE);
    }

    public void switchToNormalMode() {
    	deleteTaskBtn.setVisibility(View.GONE);
    	cancelDeleteTaskBtn.setVisibility(View.GONE);
    }
    
    public int deleteSelectTask() {
    	int totelDeleted = 0;
    	List<Task> tempTaskList = taskAdapter.getTaskList();
    	for (int i = 0; i < tempTaskList.size(); i++) {
    		Task tempTask = tempTaskList.get(i);
    		if (tempTask.getIsSelectedForDel()) {
    			db.deleteTaskById(tempTask.getTaskId(), tempTask.getMemoId());
    			totelDeleted++;
    		}
    	}
    	return totelDeleted;
    }
    
    public void startAddTaskViewActivity() {
    	Intent AddTaskIntent = new Intent(this, EditTaskViewActivity.class);
    	AddTaskIntent.putExtra(Todo.TODO_ID, todoRowId);
    	AddTaskIntent.putExtra(Task.TASK_ID, -1);
    	startActivity(AddTaskIntent);
    }
    
    private class TaskAdapter extends ArrayAdapter<Task> implements OnClickListener {
    	private List<Task> taskList;
    	private Activity context;

    	private TextView title;
    	private TextView notiDate;
		private CheckBox taskCheckbox;
		private CheckBox taskDeleteCheckbox;

        public TaskAdapter(Activity context, int resource, List<Task> taskList) {
                super(context, resource, taskList);
                this.taskList = taskList;
                this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        		View view = null;
                final Task task = taskList.get(position);
                
                if (convertView == null) {
                	LayoutInflater inflater = context.getLayoutInflater();
                	view = inflater.inflate(R.layout.task_row, null);
                	
                	title = (TextView) view.findViewById(R.id.task_row_title_txt_id);
                	title.setText(task.getTitle());
                	
                	notiDate = (TextView) view.findViewById(R.id.task_row_noti_txt_id);
                	if (task.getIsAramOn() == true) {
                		notiDate.setText(task.getStrNotiDate());
                	} else {
                		notiDate.setVisibility(View.INVISIBLE);
                	}
                	
                	taskCheckbox = (CheckBox) view.findViewById(R.id.task_check_id);
                	taskCheckbox.setChecked(task.getIsCompleted());
                	taskCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							if (isChecked == true) {
								task.setIsCompleted(true);
							} else {
								task.setIsCompleted(false);
							}
							db.updateIsCompleted(task.getTaskId(), task.getIsCompleted());
						}
					});
                	
                	taskDeleteCheckbox = (CheckBox) view.findViewById(R.id.task_delete_check_id); 
                	taskDeleteCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							if (isChecked == true) {
								task.setIsSelectedForDel(true);
							} else {
								task.setIsSelectedForDel(false);
							}
						}
					});
                	
                	
                	if (isDeleteModeOn == true) {
                		taskCheckbox.setVisibility(View.INVISIBLE);
                		taskDeleteCheckbox.setVisibility(View.VISIBLE);
                		
                	} else {
                		taskCheckbox.setVisibility(View.VISIBLE);
                		taskDeleteCheckbox.setVisibility(View.INVISIBLE);
                		
                	}
                	
                } else {
                	view = convertView;
                	
                }
                
                view.setOnClickListener(new OnTaskClickListener(context, taskList.get(position).getTaskId()));
                return view;
        }
                
        public List<Task> getTaskList() {
        	return this.taskList;
        }
                
        public void onClick(View v) {}
    }//end of class TaskAdapter

    private class OnTaskClickListener implements OnClickListener{           
    	private Activity context;
        private int taskId;
        
        OnTaskClickListener(Activity context, int taskId) {
            this.context = context;	
            this.taskId = taskId;
        }
        
        public void onClick(View v) {
        	Intent TaskViewIntent = new Intent(context, TaskViewActivity.class);
        	TaskViewIntent.putExtra(Task.TASK_ID, taskId);
        	startActivity(TaskViewIntent);
        }
    }

}
